import $data from "xcore/data";
import _ from "lodash";
import { ICmpnt } from "xcore/cmpnt";
import { watch } from "vue";

let homeId = "home"
interface IWatchPage {
    name: string,
    stopWatch: Function | undefined,
    content: string
}
const watchPages: Record<string, IWatchPage> = {
    home: { name: homeId, stopWatch: undefined, content: "" },
    page: { name: "", stopWatch: undefined, content: "" }
}



export function watchPage(pageId: string, page: ICmpnt) {
    switch (pageId.toLowerCase()) {
        case homeId:
            watchNow(watchPages.home, pageId, page);
            break;
        default:
            watchNow(watchPages.page, pageId, page);
            break;
    }
}
export function watchNow(wpage: IWatchPage, pageId: string, page: ICmpnt) {
    if (wpage && wpage.stopWatch) {
        wpage.stopWatch();
        wpage.content = "";
    }
    wpage.name = pageId;
    wpage.stopWatch = watch(page, (value: any) => {
        const currentContent = JSON.stringify($data.func.exportCmpnt(value));
        if (currentContent == wpage.content) return;//防止重复触发更新页面meta信息
        wpage.content = currentContent;
        savePage(pageId, currentContent);
    }, { deep: true })
}
// 防抖保存页面meta信息信息
let savePage=_.debounce(function (pageId: string, content: string) {
    $data.provider.meta.setMetaPage({ name: pageId, content: content });
}, 300)
